home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 226 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: news.compuserve.com!newsmaster
  2. From: <75151.03563@compuserve.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: re: tricky questions
  5. Date: 3 Jan 1996 02:32:43 GMT
  6. Organization: CompuServe Incorporated
  7. Message-ID: <4ccpsc$dnf@dub-news-svc-4.compuserve.com>
  8. NNTP-Posting-Host: dd05-017.compuserve.com
  9. Content-Type: text/plain
  10. Content-length: 1588
  11. X-Newsreader: AIR Mosaic (16-bit) version 3.10.08.25
  12.  
  13.  
  14.  RE Q1:
  15.  
  16. the default ctor of class A leaves the pointer variable , A* a, 
  17. uninitialized.  This is almost always a bad practice.  You should 
  18. program so that pointers always have a  <valid> value, ie they point
  19. somewhere sensible, or they are NULL.  In your example, when you 
  20. create an object of class B, A's default contructor is called, which leaves
  21. the member pointer variable A *a in an unknown state.  When the 
  22. object is destroyed, the destructor tries to delete am invalid pointer - a sure 
  23. recipe for disaster.  The reason you did not get the crash when you 
  24. set a= 0 in the deafult ctor is that you were doing the right thing, delete
  25. knows how to handle a NULL pointer.
  26.    A habit I've gotten into which has saved a lot of grief is to always
  27. initialize pointer variable to NULL in the member initialization list of the
  28. ctor, ie. I would have written the ctors like this.
  29.  
  30. A::A() :
  31.   a( NULL )
  32. {
  33. }
  34.  
  35. A::A(int i) :
  36.   a( NULL )
  37. {
  38.   a= new B( i );
  39. }
  40.  
  41. doing this in the second case is a bit redundant, but the habit has saved
  42. me enough grief to make it worth the effort.
  43.  
  44. Q2:
  45. I'm not as sure of this one, but... I believe that when you have an
  46. expression that is made up of several smaller expressions that are
  47. separated by commas, the overall expression takes on the value of
  48. the rightmost sub-expression.  So in your example
  49. p= (4, 5)
  50. you have two expressions ( '4' and '5' ) separated by commas, so the
  51. value of the total expression is that of the rightmost expression, which is
  52. 5.
  53.  
  54. Hope this helps,
  55. Tom Keane
  56. 75151,03563@compuserve.com
  57.  
  58.  
  59.